package com.gmrz.uap.common.db;

import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DataSourceJndiMasterSlaveOnlyImpl implements DataSourceShardingFactory {

    @Override
    public DataSource getInstance() throws SQLException {

        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration();
        masterSlaveRuleConfig.setName(DataSourceShardingConst.getConfigInfo(DataSourceShardingConst.DATASOURCE_MASTERSLAVE_NAME));
        masterSlaveRuleConfig.setMasterDataSourceName(DataSourceShardingConst.getConfigInfo(DataSourceShardingConst.DATASOURCE_MASTERSLAVE_MASTER_JNDI));
        masterSlaveRuleConfig.setSlaveDataSourceNames(DataSourceShardingConst.getJndiListFromString(DataSourceShardingConst.getConfigInfo(DataSourceShardingConst.DATASOURCE_MASTERSLAVE_SLAVE_JNDI_LIST)));
        return MasterSlaveDataSourceFactory.createDataSource(createDataSourceMap(), masterSlaveRuleConfig, new ConcurrentHashMap<String, Object>());
    }

    private static Map<String, DataSource> createDataSourceMap() {
        String masterJndi = DataSourceShardingConst.getConfigInfo(DataSourceShardingConst.DATASOURCE_MASTERSLAVE_MASTER_JNDI);
        String[] slaveJndiList = DataSourceShardingConst.getJndiSharding(DataSourceShardingConst.DATASOURCE_MASTERSLAVE_SLAVE_JNDI_LIST);

        final Map<String, DataSource> result = new HashMap<String, DataSource>();
        result.put(masterJndi, DataSourceShardingConst.getDataSourceForJndi(masterJndi)); //主数据库源

        for (String slaveJndiName : slaveJndiList) { //从数据库源
            result.put(slaveJndiName, DataSourceShardingConst.getDataSourceForJndi(slaveJndiName));
        }

        return result;
    }

}